package system;

import static java.lang.System.out;

import aws.Machine;
import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;


/**
 * start & stop a Master and set of Workers
 *
 * @author Pete Cappello
 */
public class Cluster
{
    private static final int PUBLIC_DOMAIN_NAME  = 0;
    private static final int PRIVATE_DOMAIN_NAME = 1;
    
    public ClientToMaster start( boolean isEc2, int numWorkers ) throws RemoteException
    {
        
        ClientToMaster master = null;
        String[] domainNames = { null, null };
        if ( isEc2 )
        {
            domainNames = Machine.startMaster( numWorkers );
            try
            {
                wait( 30000 ); // wait for Master to start
            }
            catch ( InterruptedException ignore ) {} 
            String url = "//" + domainNames[ PUBLIC_DOMAIN_NAME ] + ":" + Master.PORT + "/" + Master.SERVICE_NAME;	
            try 
            {
                master = (ClientToMaster) Naming.lookup( url );
            } 
            catch ( Exception exception ) 
            {
                out.println( "Exception: " + url + " -- " + exception.getMessage() );
                exception.printStackTrace();;
                System.exit( 1 );
            }
        }
        else
        {          
            master = new LocalMaster();
        }
        master.makeWorkers( numWorkers, domainNames[ PRIVATE_DOMAIN_NAME ] );        
        return master;
    }
    
    public static void stop( boolean isEc2 )
    {
        if ( isEc2 )
        {
            // for each worker,
            {
                Machine.stop( /* parameter identifies which machine to stop */ );
            }
            
            // stop EC2 master machine
            Machine.stop( /* parameter identifies which machines to stop */ );
        }
    }
}
